<?php

namespace app\controllers\h5\uni;

use app\commission\Order;
use app\controllers\h5\base\H5Controller;
use app\controllers\wx\services\Wx;
use app\models\AdminSupplier;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\SupplierCategory;
use app\models\SupplierImageDesc;
use app\models\system\SetFlow;
use app\models\system\SetQrcode;
use app\models\system\SetSwiper;
use app\models\order\Order as MerchantOrder;
use app\models\system\SetWx;
use app\models\user\User;
use app\util\Qrcode;
use app\util\Request;
use yii\imagine\Image;

class OfflineController extends H5Controller
{
    public function actionIndex()
    {
        // 商家轮播图
        $swiper = SetSwiper::find()
            ->where(['status' => SetSwiper::$statusMapping['OK']])
            ->andWhere(['category_id' => 11])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['image'])
            ->asArray()
            ->all();


        $set = SetFlow::getLastOne()->recommend_num;
        // 商家列表
        $merchant = AdminSupplier::find()
            ->where(['status' => 1])
            ->limit($set)
            ->with(['category', 'descImage', 'descImage.image'])
            ->asArray()
            ->all();

        // 商家分类
        // 如果没有产品则不显示
        $ids = Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            ->andWhere(['>=', 'supplier_id', 1])
            ->select(['category_id'])
            ->column();

        $category = SupplierCategory::find()
            ->where(['status' => 1])
            ->andWhere(['id' => $ids])
            ->with(['image.image'])
            ->asArray()
            ->all();

        return $this->successEncode([
            'swiper' => $swiper,
            'merchant' => $merchant,
            'category' => $category,
        ]);
    }

    public function actionProduct()
    {
        $address_id = $this->post('Address_id');
        // var_dump($address_id);exit;
        if (!$address_id) {
            // return $this->successEncode([
            //     $this->list => [],
            //     $this->totalCount => 0,
            //     $this->totalPage => 0,
            //     $this->currentPage => 1
            // ]);

            // 如果没有选地区
            // 则默认全部显示
        }


        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        // 地区
        $supplier_ids = AdminSupplier::find()
            ->where(['status' => 1])
            ->andWhere(['address_id' => $address_id])
            ->select(['id'])
            ->column();

        // var_dump($supplier_ids);exit;

        // 产品分区
        $area_id = 3;

        // 审核处理一下
        $set = SetFlow::getLastOne();
        if ($set->wx == 1) {
            $query = Product::find()
                ->where(['status' => Product::$statusMapping['OK']]);
        } else {
            $query = Product::find()
                ->where(['status' => Product::$statusMapping['OK']])
            // ->andWhere(['area_id' => $area_id])
            ->andWhere(['supplier_id' => $supplier_ids]);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['mainImage'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);

    }

    // 商家分类商品
    public function actionSupplierCategoryProduct()
    {
        $category_id = $this->post('id');


        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            // 这里的分类共用了, 所以要是供应商产品
            ->andWhere(['category_id' => $category_id])
            ->andWhere(['>=', 'supplier_id', 1]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['mainImage'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);


    }

    // 已完成核销的商家订单
    public function actionMerchantOrder()
    {
        $merchant_id = $this->post('merchant_id');

        // 核销的只需要完成的,
        // 线下支付的, 需要看来未支付的
        $pay = $this->post('pay', '');

        // var_dump($merchant_id);exit;


        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = MerchantOrder::find()
            // ->where(['status' => MerchantOrder::$statusMapping['FINISH']])
            ->where(['supplier_id' => $merchant_id]);

        if ($pay != 'pay') {
            $query->andWhere(['status' => MerchantOrder::$statusMapping['FINISH']]);
            $query->andWhere(['!=', 'pay_type', '121']);
        } else {
            $query->andWhere(['pay_type' => '121']);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['update_time' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['item', 'item.product', 'item.product.mainImage'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    // 扫码核销
    public function actionMerchantScan()
    {
        $id = $this->post('order_id');
        $order = MerchantOrder::find()
            ->where(['id' => $id])
            ->one();

        // var_dump($id);exit;

        if ($order) {

            if ($order->status == MerchantOrder::$statusMapping['FINISH']) {
                return $this->fail('此订单已经核销过了');
            }

            $order->status = MerchantOrder::$statusMapping['FINISH'];
            $order->update_time = date('Y-m-d H:i:s');
            $order->save();

            return $this->success();
        }

        return $this->fail();
    }

    // 商家详情
    public function actionShop()
    {
        $id = $this->post('id');
        $supplier = AdminSupplier::find()
            ->where(['id' => $id])
            ->select(['id', 'mobile', 'desc', 'address', 'name', 'is_shop'])
            ->asArray()
            ->one();
        $desc = SupplierImageDesc::find()
            ->where(['supplier_id' => $id])
            ->with(['image'])
            ->asArray()
            ->one();

        return $this->successEncode([
            'desc' => $desc,
            'supplier' => $supplier,
        ]);
    }

    // 商家收款码
    public function actionMerchantPay()
    {
        $merchant_id = $this->post('merchant_id');
        $scene = 'merchant-' . $merchant_id;

        $base = \Yii::$app->getBasePath();
        $path = $base . '/web/merchant-pay/' . $scene . '.jpg';

        if (!file_exists($path)) {
            // get
            // $getAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$set->app_id}&secret={$set->app_secret}";
            // $result = Request::get($getAccessToken);
            $access_token = Wx::getAccessToken();

            // post
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            // $result = Request::post($url, json_encode(['scene' => $scene, 'page' => $page]));
            $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 375])); // 最小也是280
            // $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 280, 'is_hyaline' => true]));

            // todo 这里token可能过期

            // var_dump($result);exit;

            $dir = dirname($path);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
                chmod($dir, 0777);
            }

            // wx qrcode
            file_put_contents($path, $result);

            // sleep(1);
        }

        // 商家信息
        $info = AdminSupplier::find()
            ->where(['id' => $merchant_id])
            ->select(['name', 'mobile', 'id'])
            ->asArray()
            ->one();

        return $this->successEncode([
            'path' => '/merchant-pay/' . $scene . '.jpg',
            'scene' => $scene,
            'info' => $info,
        ]);

    }

    // 创建扫码支付订单
    public function actionMerchantPayRun()
    {
        $merchant_id = $this->post('merchant_id');
        $amount = $this->post('amount', 0);

        if ($amount <= 0) {
            return $this->fail('金额错误');
        }

        $transaction = \Yii::$app->db->beginTransaction();

        try {

            // $user = User::findOne(['id' => $this->user->id]);


            // 创建订单
            $order = new MerchantOrder();
            $order->sn = MerchantOrder::generateSn();

            // 云仓提供(也对应数量)
            $order->user_address = 0;
            $order->user_id = $this->user->id;
            $order->total_pay = $amount;
            $order->use_money = $amount;
            $order->supplier_id = $merchant_id;
            $order->pay_type_name = '线下扫码';
            $order->pay_type = '121';
            $order->request_params = '';
            $order->status = MerchantOrder::$statusMapping['NON_PAYMENT'];
            $order->total_quantity = 1;
            $r=$order->save();
            if (!$r) {
                throw new \Exception($order->getFirstError());
            }

            $item = new OrderItem();
            $item->order_id = $order->id;
            $item->quantity = 1;
            $item->product_id = 0;
            $item->product_sku_id = 0;
            $item->selected_sku_value = '';
            $item->selected_sku_text = '';
            $item->freight = 0;
            $item->price = 0;
            $item->score = 0;
            $item->save();

            $transaction->commit();
            return $this->successEncode([
                'order_id' => $order->id
            ]);
        } catch (\Exception $e) {

            $transaction->rollBack();
            return $this->fail($e->getMessage() . ' ' . $e->getLine(). ' ' . $e->getFile());
            return $this->fail($e->getMessage());
        }

    }

    // 同城商家
    public function actionCityMerchant()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = AdminSupplier::find()
            ->where(['status' => 1]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['category', 'descImage', 'descImage.image'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }
}